<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="耗材编码">
          <el-input
            v-model="searchParam.consumeCode"
            placeholder="请输入耗材编码"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="物料号">
          <el-select
            v-model="searchParam.materialId"
            placeholder="请选择物料号"
            filterable
            clearable
          >
            <el-option
              v-for="item in materialOptions"
              :key="item.id"
              :label="`${item.materialCode}-${item.materialName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="耗材类型">
          <el-select
            v-model="searchParam.materialGroupCode"
            placeholder="请选择耗材类型"
            filterable
            clearable
          >
            <el-option
              v-for="item in Array.from(
                new Map(
                  materialOptions.map((item) => [
                    item.materialGroupCode,
                    item.materialGroupCode,
                  ])
                ).values()
              )"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生产状态">
          <el-select
            v-model="searchParam.status"
            placeholder="请选择耗材类型"
            filterable
            clearable
          >
            <el-option
              v-for="item in useDictionary('csmStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          class="ml-3"
          @click="
            useDownload(
              '/eam/csmproductrecord/export',
              '耗材生产记录',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
        <el-button type="success" @click="excelBoxOpen">导入 </el-button>
        <el-dialog
          :close-on-click-modal="false"
          title="耗材生产记录数据导入"
          v-model="excelBox"
          width="555px"
        >
          <div>
            <el-button
              @click="
                useDownload(
                  '/eam/csmproductrecord/exportTemp',
                  '耗材生产记录上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              耗材生产记录上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="耗材编码"
          prop="consumeCode"
          min-width="200"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="耗材物料号"
          prop="materialCode"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="耗材名称"
          prop="materialName"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="类型编码"
          prop="materialGroupCode"
          min-width="250"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="类型名称"
          prop="materialGroupName"
          min-width="250"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="生产状态"
          prop="status"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{
              useDictionary("csmStatus").find(
                (item) => item.value === scope.row.status
              )?.label
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="产品物料号"
          prop="productCode"
          min-width="150"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="使用设备"
          prop="equipCode"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="安装时间"
          prop="upTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="卸载时间"
          prop="downTime"
          min-width="180"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="使用位置"
          prop="equipPosition"
          min-width="100"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="使用寿命(%)"
          prop="workLife"
          min-width="120"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="使用次数"
          prop="workCount"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useCsmSelectOptionsStore } from "@/views/eam/csm/store/csmSelectOptionsStore";
import { useRoute } from "vue-router";

defineOptions({
  name: "EAMCSMPRODUCTRECORD",
  inheritAttrs: false,
});

const optionsStore = useCsmSelectOptionsStore();
const materialOptions = computed(() => optionsStore.materialOptions);
// 请求参数
const requestApi = "/eam/csmproductrecord/queryByPage";

const route = useRoute();
// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  materialId: "",
  status: "",
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError
);

onMounted(() => {
  console.log("searchParam.value.consumeCode", route.query);
  if (route.query.consumeCode && route.query.consumeCode !== "null") {
    searchParam.value.consumeCode = route.query.consumeCode;
  }
  getTableList();
  optionsStore.queryMaterialList();
});

// 导入excel
const uploadApi = "/eam/csmproductrecord/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}
</script>
